<template>
  <el-row>
    <el-col :span="24" v-if="isComments">
      <div class="comments-add">
        <el-form :model="setCommentsForm" ref="setCommentsForm" :rules="setCommentsFormRules" label-position="top" label-width="100px">
          <el-form-item prop="commentsText">
            <el-input type="textarea" maxlength="100" minlength="2" show-word-limit placeholder="请输入评论内容" :rows="5" v-model="setCommentsForm.commentsText"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="setCommentsFormSubmit">发表评论</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <el-col :span="24">
      <el-row>
        <client-only>
          <el-skeleton :animated="true" :loading="comments_loading" :rows="0">
            <template slot="template">
              <el-col :span="24">
                <div class="comments-info">
                  <div class="comments-avatar">
                    <el-skeleton-item variant="image" style="width: 50px; height: 50px; margin: 0 auto;" />
                  </div>
                  <div class="comments-text">
                    <div class="pointer f-gray-color">
                      <el-skeleton-item variant="h3" style="width: 60px;margin-bottom: 0" />
                      <el-skeleton-item variant="h3" style="width: 60px;margin-bottom: 0" />
                    </div>
                    <div><el-skeleton-item variant="p" style="width: 200px" /></div>
                  </div>
                </div>
              </el-col>
            </template>
            <template>
              <template v-if="isShow">
                <el-col :span="24" v-for="(item,index) in commentsList" :key="index">
                  <div class="comments-info" v-if="!isUser">
                    <div class="comments-avatar">
                      <router-link :to="'/user/' + item.userId">
                        <el-avatar shape="square" icon="el-icon-user-solid" :size="50" :src="(item.commentsAvatar == null) ? '': imgPrefix + item.commentsAvatar"></el-avatar>
                      </router-link>
                    </div>
                    <div class="comments-text">
                      <div class="pointer f-gray-color">
                        <span><router-link :to="{path:'/user/' + item.userId}">{{ item.commentsNickName }}</router-link></span>
                        <el-tooltip class="item" effect="dark" :content="item.createTime" placement="top">
                          <span style="font-size: 12px">{{ (item.createTime == null) ? '':$utils_formatTime.timeStr(item.createTime) }}</span>
                        </el-tooltip>
                      </div>
                      <div>{{ item.commentsText }}</div>
                      <div style="font-size: 12px" class="f-gray-color">
                        地点：{{ item.commentsIpadderss }}&nbsp;
                        设备：{{ item.commentsSystem }}&nbsp;
                        浏览器：{{ item.commentsBrowser }}&nbsp;
                        <div>
                          <el-button v-if="isLogin && userInfo.userName != item.createBy" @click="replyComments(item.id, item.commentsNickName)" type="text" size="mini">回复</el-button>
                          <el-popconfirm v-if="isLogin && userInfo.userName == item.createBy" @confirm="delComments(item.id)" title="确定删除当前评论吗？"icon="el-icon-info" icon-color="red">
                            <el-button type="text" slot="reference" size="mini">删除</el-button>
                          </el-popconfirm>
                        </div>
                      </div>
                      <el-card class="mg-b-10" :body-style="{padding: '10px',width: '100%'}" v-if="item.children.length > 0" shadow="never">
                        <div class="comments-info" v-for="(items, index) in item.children" :key="index">
                          <div class="comments-avatar">
                            <router-link :to="'/user/' + items.userId">
                              <el-avatar shape="square" icon="el-icon-user-solid" :size="50" :src="(items.commentsAvatar == null) ? '': imgPrefix + items.commentsAvatar"></el-avatar>
                            </router-link>
                          </div>
                          <div class="comments-text">
                            <div class="pointer f-gray-color">
                              <span>
                                <router-link :to="{path:'/user/' + items.userId}">{{ items.commentsNickName }}</router-link>
                                回复
                                <router-link v-if="items.btUsername == null" :to="{path:'/user/' + item.userId}">{{ item.commentsNickName }}</router-link>
                                <router-link v-else :to="{path:'/user/' + items.btUserId}">{{ items.btUsername }}</router-link>
                              </span>
                              <el-tooltip class="item" effect="dark" :content="items.createTime" placement="top">
                                <span style="font-size: 12px">{{ (items.createTime == null) ? '':$utils_formatTime.timeStr(items.createTime) }}</span>
                              </el-tooltip>
                            </div>
                            <div>{{ items.commentsText }}</div>
                            <div style="font-size: 12px" class="f-gray-color">
                              地点：{{ items.commentsIpadderss }}&nbsp;
                              设备：{{ items.commentsSystem }}&nbsp;
                              浏览器：{{ items.commentsBrowser }}&nbsp;
                              <div>
                                <el-button v-if="isLogin && userInfo.userName != items.createBy" @click="replyComments(item.id, item.commentsNickName, items.createBy)" type="text" size="mini">回复</el-button>
                                <el-popconfirm v-if="isLogin && userInfo.userName == items.createBy" @confirm="delComments(items.id)" title="确定删除当前评论吗？"icon="el-icon-info" icon-color="red">
                                  <el-button type="text" slot="reference" size="mini">删除</el-button>
                                </el-popconfirm>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="text-center overflow-scroll">
                          <el-row>
                            <el-col :span="24">
                              <el-pagination
                                background
                                layout="total, prev, pager, next, jumper"
                                :small="true"
                                :total="item.children.length"
                                :page-size="5">
                              </el-pagination>
                            </el-col>
                          </el-row>
                        </div>
                      </el-card>
                    </div>
                  </div>
                  <el-card v-else class="mg-b-10 pointer" :body-style="{padding: '10px'}" shadow="hover" style="border: none">
                    <div class="comments-info" style="margin-bottom: 0">
                      <div class="comments-avatar">
                        <el-avatar shape="square" icon="el-icon-user-solid" :size="50" :src="(item.commentsAvatar == null) ? '': imgPrefix + item.commentsAvatar"></el-avatar>
                      </div>
                      <div class="comments-text">
                        <div class="pointer f-gray-color">
                          <span class="f-black-color">{{ item.commentsNickName }}</span>
                          <el-tooltip class="item" effect="dark" :content="item.createTime" placement="top">
                            <span style="font-size: 12px">{{ (item.createTime == null) ? '':$utils_formatTime.timeStr(item.createTime) }}</span>
                          </el-tooltip>
                        </div>
                        <div><a href="javascript:;" @click="goLinks('/read/' + item.webId)">{{ item.commentsText }}</a></div>
                        <div style="font-size: 12px" class="f-gray-color">
                          地点：{{ item.commentsIpadderss }}&nbsp;
                          设备：{{ item.commentsSystem }}&nbsp;
                          浏览器：{{ item.commentsBrowser }}&nbsp;
                          <div>
                            <el-popconfirm v-if="isLogin && userInfo.userName == item.createBy" @confirm="delComments(item.id)" title="确定删除当前评论吗？"icon="el-icon-info" icon-color="red">
                              <el-button type="text" slot="reference" size="mini">删除</el-button>
                            </el-popconfirm>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
                <el-dialog
                  :title="'您正在回复：' + replyCommentsTitle"
                  :visible.sync="replyCommentsDialogVisible"
                  width="35%"
                  center>
                  <el-form :model="replyCommentsForm" ref="replyCommentsForm" :rules="replyCommentsFormRules" label-position="top" label-width="100px">
                    <el-form-item prop="commentsText">
                      <el-input type="textarea" maxlength="100" minlength="2" show-word-limit placeholder="请输入回复内容" :rows="5" v-model="replyCommentsForm.commentsText"></el-input>
                    </el-form-item>
                  </el-form>
                  <span slot="footer" class="dialog-footer">
                    <el-button size="small" @click="replyCommentsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" size="small" @click="replyCommentsFormSubmit">回 复</el-button>
                  </span>
                </el-dialog>
              </template>
              <el-col v-if="!isShow" :span="24">
                <el-empty :image-size="200" description="暂无评论"></el-empty>
              </el-col>
            </template>
          </el-skeleton>
        </client-only>
        <el-col :span="24" v-if="isShow">
          <div class="text-center overflow-scroll">
            <el-row class="pd-10">
              <el-col :span="24">
                <el-pagination
                  background
                  layout="total, prev, pager, next, jumper"
                  :small="true"
                  :total="commentsTotal"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="currentChange">
                </el-pagination>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import {mapState} from "vuex";

export default {
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      isLogin: state => state.user.isLogin
    })
  },
  props: {
    //是否显示发表评论
    isComments: {
      type: Boolean,
      default: true
    },
    //链接ID
    linksId: {
      type: Number,
      default: null
    },
    //用户名称
    username: {
      type: String,
      default: null
    },
    //是否显示在用户中心的样式
    isUser: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return{
      //图片链接前缀
      imgPrefix: process.env.NUXT_APP_BASE_API,
      //评论渲染加载
      comments_loading: true,
      //是否显示评论列表
      isShow: false,
      //评论列表
      commentsList: [],
      //评论总条数
      commentsTotal: 0,
      //评论每页显示条数
      pageSize: 10,
      //当前页数
      currentPage: 1,
      //评论表单
      setCommentsForm: {
        commentsText: null
      },
      //评论表单校验
      setCommentsFormRules: {
        commentsText: [
          { required: true, message: '请输入评论内容', trigger: 'blur' },
          { min: 2, max: 100, message: '评论长度在 2 到 100 个字符', trigger: 'blur' }
        ]
      },
      //评论回复
      replyCommentsDialogVisible: false,
      //评论回复标题
      replyCommentsTitle: null,
      //评论回复表单
      replyCommentsForm: {
        pId: null,
        commentsText: null,
        bUsername: null
      },
      //评论回复表单校验
      replyCommentsFormRules: {
        commentsText: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 2, max: 100, message: '回复长度在 2 到 100 个字符', trigger: 'blur' }
        ]
      },
    }
  },
  mounted() {
    this.getCommentsList();
  },
  methods: {
    //翻页
    currentChange(page){
      this.currentPage = page;
      this.getCommentsList();
    },
    //获取评论列表
    getCommentsList(){
      this.$api_comments.getList(this.linksId, this.username, this.currentPage, this.pageSize).then(res => {
        if(res.code === 200){
          this.commentsList = res.rows;
          this.commentsTotal = res.total;
          this.isShow = res.total > 0;
          this.comments_loading = false;
        }
      })
    },
    //发表评论
    setCommentsFormSubmit(){
      this.$refs['setCommentsForm'].validate((valid) => {
        if (valid) {
          this.$api_comments.add(this.linksId, this.setCommentsForm.commentsText).then(res => {
            if(res.code === 200){
              this.$message.success({
                message: '评论成功',
                duration: process.env.MSG_TIME
              });
              this.setCommentsForm.commentsText = null;
              this.getCommentsList();
            }
          })
        }else{
          this.$message.error("请输入评论内容");
          return false;
        }
      });
    },
    //链接跳转
    goLinks(url){
      this.$router.push(url);
    },
    //删除评论
    delComments(id){
      this.$api_comments.delete(id).then(res => {
        if(res.code === 200){
          this.$message({
            message: '删除成功',
            type: "success",
            duration: process.env.MSG_TIME
          });
          this.getCommentsList();
        }else{
          this.$message.error(res.msg);
        }
      });
    },
    //回复评论
    replyComments(id, title, username){
      this.replyCommentsDialogVisible = true;
      this.replyCommentsTitle = title;
      this.replyCommentsForm.pId = id;
      if(username){
        this.replyCommentsForm.bUsername = username;
      }
    },
    //回复评论提交
    replyCommentsFormSubmit(){
      this.$refs['replyCommentsForm'].validate((valid) => {
        if (valid) {
          this.$api_comments.add(this.linksId, this.replyCommentsForm.commentsText, this.replyCommentsForm.pId, this.replyCommentsForm.bUsername).then(res => {
            if(res.code === 200){
              this.$message.success({
                message: '回复成功',
                duration: process.env.MSG_TIME
              });
              this.replyCommentsForm.pId = null;
              this.replyCommentsForm.commentsText = null;
              this.getCommentsList();
            }
          })
        }else{
          this.$message.error("请输入回复内容");
          return false;
        }
        this.replyCommentsDialogVisible = false;
      });
    }
  }
}
</script>

<style scoped>
.comments-info{
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
}
.comments-avatar{
  margin-right: 15px;
}
.comments-text{
  width: 100%;
}
.comments-text div{
  margin-bottom: 10px;
  font-size: 14px;
}
.comments-text div:last-child{
  margin-bottom: 0;
}
</style>
